import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class Server {
    private DatagramSocket socket = null;//用来接收和发送数据报
    //构造方法,当创建这个类就执行
    public Server(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");

        //服务器会处于一直执行状态
        while(true){
            //1. 读取并解析
            DatagramPacket requestgramPacket = new DatagramPacket(new byte[4090],4090);
            socket.receive(requestgramPacket);//向数据报(requestgramPacket)中存数据
            //将读到的二进制数据转换为字符串
            String requset = new String(requestgramPacket.getData(),0,requestgramPacket.getLength());
            //2. 具体操作
            String response = process(requset);
            //3. 把操作后的结果返回
            //创建一个数据报接收处理后的结果
            DatagramPacket responsePage = new DatagramPacket(response.getBytes(),response.getBytes().length,
                    requestgramPacket.getSocketAddress());//要加上接收方的ip地址和端口号
            socket.send(responsePage);

            System.out.printf("[%s:%d] req: %s, resp: %s\n", requestgramPacket.getAddress().toString(), requestgramPacket.getPort(),
                    requestgramPacket, response);
        }
    }
    private String process(String requset) {
        return  requset;
    }
    public static void main(String[] args) throws IOException {
        Server server  = new Server(9090);
        server.start();
    }
}
